﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System;
using Wy_VoteSys.Models.Database;
using Wy_VoteSys.Service;
using Wy_VoteSys.Models;

namespace Wy_VoteSys.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly Wy_VoteSysContext _db;
        private readonly IJWTService _jwtService;
        public UserController(Wy_VoteSysContext db, IJWTService jwtService)
        {
            _db = db;
            _jwtService = jwtService;
        }
        /// <summary>
        /// 用户注册接口 输入：邮箱，密码 输出：注册成功或失败消息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Register(RegisterRequest request)
        {
        
            //1、两次密码是否一致
            if (request.Password != request.CirPassword)
                return "两次密码输入不一致";
            //2、邮箱在数据库是否存在 去数据库查一下有没有这个邮箱
            if (_db.Users.Any(x => x.Email == request.Email))
                return "邮箱已存在";

            //数字随机字符串
            var salt = new Random().Next(1000, 10000);

            //加入一步  把明文密码  转换成 md5字符串
            var md5 = MD5Helper.MD5Encrypt32(request.Password + salt);

            //3、添加用户到数据库
            var user = new User
            {
                CreateTime = DateTime.Now,
                Email = request.Email,
                Password = md5,
                Salt=salt.ToString(),
            };
            _db.Users.Add(user);
            //保存更改
            var row = _db.SaveChanges();
            if (row > 0)
                return "注册成功";
            return "注册失败";
        }
        /// <summary>
        /// 登录接口 用户使用手机号码，密码进行登录，登录后可访问需要授权的页面）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Login(LoginRequest request)
        {
            //1、用账号（手机号码）查询用户
            var user = _db.Users.FirstOrDefault(x =>x.Email == request.Email);
            //2、判断用户是否存在
            if (user == null)
                return "用户不存在";
            //3、判断用户密码是否正确

            //当用户表密码字段使用char(20)   
            //123456
            //输入的密码 "123456"
            //   ！= 成立
            //数据库密码 "123456           "
            //                                   输入密码 明文 + 数据库里盐值
            var md5 = MD5Helper.MD5Encrypt32(request.Password + user.Salt);

            //     md5                      明文密码
            if (user.Password != md5)
                return "密码不正确";
            //4、创建token
            return _jwtService.CreateToken(user.UserId.ToString(), user.Email);
        }

    }
}
